<template>
<div>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form v-loading="formLoading" :model="dataForm" inline :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">

       <el-form-item label="所属基地" prop="deptId">
          <el-input  v-model="dataForm.deptName" v-popover:deptListPopover readonly="true" placeholder="所属基地"></el-input>

          <!-- <el-tooltip class="item" style="width:10%;" effect="dark" content="更换基地将会清除田块" placement="top-start">
          <el-button>*</el-button>
         </el-tooltip> -->

            <el-popover ref="deptListPopover" placement="bottom-start" trigger="click" @hide="hidep()">
              <el-tree
                ref="deptListTree" node-key="id"
                show-checkbox
                :data="deptList"
                :props="deptListTreeProps"
                @check-change="checkChange"
                :check-strictly="true"
                :default-expand-all="true"
                :highlight-current="true"
                :expand-on-click-node="false"
              >
              </el-tree>
          </el-popover>
        </el-form-item>

     <el-form-item label="应用田块" prop="relationFarmlandIds">
          <div @click="changeInput">
            <el-input v-model="dataForm.farmlandInfoIdsname" readonly=""  placeholder="选择应用田块"></el-input>
          </div>
    </el-form-item>

    <el-form-item label="规则名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="规则名称"></el-input>
    </el-form-item>

    <el-form-item label="告警类型 " prop="type">
      <el-select class="form-item" v-model="dataForm.type" placeholder="请选择">
            <el-option
              v-for="item in ztoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
      </el-form-item>

      <el-form-item label="告警语" prop="name">
        <el-input type="textarea" :rows="3" style="width:500px" v-model="yujingyu" placeholder="告警语"></el-input>
      </el-form-item>



      <el-form-item label="作用开始时间" prop="startTime">
        <!-- <el-input v-model="dataForm.startTime" placeholder="作用时间开始"></el-input> -->
        <el-date-picker
          class="form-item"
              v-model="dataForm.startTime"
              type="datetime"
              placeholder="作用开始时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              >
            </el-date-picker>
      </el-form-item>
      <el-form-item label="作用结束时间" prop="endTime">
        <!-- <el-input v-model="dataForm.endTime" placeholder="作用时间结束"></el-input> -->
        <el-date-picker
          class="form-item"
              v-model="dataForm.endTime"
              type="datetime"
              placeholder="作用结束时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              >
            </el-date-picker>
      </el-form-item>

      <el-form-item label="标准值" prop="standard">
        <el-input v-model="dataForm.standard" placeholder="标准值"></el-input>
      </el-form-item>

      <el-form-item label="告警级别" prop="strs">
            <el-table
              :data="strs"
              border
              style="width: 480px">
              <el-table-column
                prop="value"
                label="警告级别"
                width="200">
              </el-table-column>
              <el-table-column
                prop="lowest"
                width="140"
                label="最低值">
                <template slot-scope="scope">
                  <el-input-number style="width:100%" v-model="scope.row.lowest" placeholder="低于此值触发" controls-position="right" :min="0" :max="1000000"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                prop="highest"
                width="140"
                label="最高值">
                <template slot-scope="scope">
                   <el-input-number style="width:100%" v-model="scope.row.highest" placeholder="高于此值触发" controls-position="right" :min="0" :max="1000000"></el-input-number>
                </template>
              </el-table-column>
            </el-table>
      </el-form-item>

      <el-form-item label=" " prop="strs" style="">
        <el-alert
          :closable="false"
          title=" * 当设备采集数值低于告警级别设置的最低值或者高于最高值触发告警"
          type="warning">
        </el-alert>
      </el-form-item>

    <!-- <div v-for="item in strs" :key="item.id" :label="item.value" :value="item.id">
      <el-form-item style="width:220px" label="值低于" prop="lowest" label-width="50">
        <el-input style="width:100px" v-model="item.lowest" placeholder="最低"></el-input> &nbsp;&nbsp;触发
      </el-form-item>
      <el-form-item style="width:220px" label="值高于" prop="highest" label-width="50">
        <el-input style="width:100px" v-model="item.highest" placeholder="最高"></el-input> &nbsp;&nbsp;触发
      </el-form-item>
    </div> -->

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button v-loading="formLoading" type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
      <bussfarmlandinfoSelect v-if="bussfarmlandinfoSelectVisible" ref="bussfarmlandinfoSelect"
        @bussFarmlandInfoSelectChange="bussFarmlandInfoSelectChange"></bussfarmlandinfoSelect>

    </div>
</template>

<script>
import { treeDataTranslate } from '@/utils'
 import bussfarmlandinfoSelect from './bussfarmlandinfoSelect'
  export default {
    data () {
      return {
        visible: false,
        formLoading: false,
         demoVisible: false,
         bussfarmlandinfoSelectVisible:false,
         deptList: [],
         farmlandInfoIdsname:'',
        deptListTreeProps: {
          label: 'name',
          children: 'children',
          disabled: function(data, node){
            return data.type == 1 ? false :true
          }
        },
        dataForm: {
          id: 0,
          deptId: '',
          warningLev: '',
          name: '',
          lowest: '',
          deptId: '',
          deptName:'',
          farmlandInfoIdsname:'',
          parentName:'',
          highest: '',
          standard: '',
          type: '',
          startTime: '',
          endTime: '',
          relationFarmlandIds: '',
          createId: '',
          createName: '',
          createTime: '',
          updateId: '',
          updateTime: '',
          updateName: '',
          version: '',
          gcFlag: ''
        },
        strs:[],
        yujingyu: '',
        ztoptions: [{
          value: Number('0'),
          label: '田间水位'
        }, {
          value: Number('1'),
          label: ' 田间水温'
        }, {
          value: Number('2'),
          label: ' 风力风向'
        }, {
          value: Number('3'),
          label: ' 太阳能蓄电池'
        }, {
          value: Number('4'),
          label: ' 光传感器'
        }],

        dataRule: {
          deptId: [
            { required: true, message: '基地不能为空', trigger: 'change' }
          ],
          // warningLev: [
          //   { required: true, message: '告警级别 字典不能为空', trigger: 'blur' }
          // ],
          name: [
            { required: true, message: '规则名称不能为空', trigger: 'blur' }
          ],
          standard: [
            { required: true, message: '标准值不能为空', trigger: 'blur' }
          ],
          type: [
            { required: true, message: '告警类型不能为空', trigger: 'blur' }
          ],
          startTime: [
            { required: true, message: '作用开始时间不能为空', trigger: 'blur' }
          ],
          endTime: [
            { required: true, message: '作用结束时间不能为空', trigger: 'blur' }
          ],
          relationFarmlandIds: [
            { required: true, message: '关联田块不能为空', trigger: 'change' }
          ]
        },
         menuList: [],
         multipleSelection: [],
         updatedeptid:'',
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        key: '',
        gjjbList:[],
        oldvalue:'',
        menuListTreeProps: {
          label: 'name',
          children: 'children'
        }

      }
    },
     components: {
      bussfarmlandinfoSelect
    },
    methods: {
      init (id) {
        this.dataForm.relationFarmlandIds = ''
        this.dataForm.farmlandInfoIdsname = ''
        this.dataForm.deptId = ''
        this.dataForm.deptName = ''
        this.oldvalue == ''

        // 获取告警级别字典列表
        this.$http({
          url: this.$http.adornUrl('/sys/dict/select'),
          method: 'get',
          params: this.$http.adornParams({
              "type": "alarm_level_00"
          })
        }).then(({data}) => {
          var self=this

          this.gjjbList = data.list
          this.strs = []

          this.gjjbList.forEach(function(v){
              self.strs.push({'id':v.id,'value':v.value,'orderNum':v.orderNum})
          })
        })

        this.dataForm.id = id || 0
        this.$http({
          url: this.$http.adornUrl('/sys/dept/select2'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {

          this.deptList = treeDataTranslate(data.deptList, 'id')
        }).then(() => {
        this.visible = true
        this.formLoading = false
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
           })
          }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/buss/bussrtuwarningrole/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.deptId = data.bussRtuWarningRole.deptId
                this.dataForm.warningLev = data.bussRtuWarningRole.warningLev
                this.dataForm.name = data.bussRtuWarningRole.name
                this.dataForm.lowest = data.bussRtuWarningRole.lowest
                this.dataForm.highest = data.bussRtuWarningRole.highest
                this.dataForm.standard = data.bussRtuWarningRole.standard
                this.dataForm.type = data.bussRtuWarningRole.type
                this.dataForm.startTime = data.bussRtuWarningRole.startTime
                this.dataForm.endTime = data.bussRtuWarningRole.endTime
                this.dataForm.relationFarmlandIds = data.bussRtuWarningRole.relationFarmlandIds
                this.dataForm.createId = data.bussRtuWarningRole.createId
                this.dataForm.createName = data.bussRtuWarningRole.createName
                this.dataForm.createTime = data.bussRtuWarningRole.createTime
                this.dataForm.updateId = data.bussRtuWarningRole.updateId
                this.dataForm.updateTime = data.bussRtuWarningRole.updateTime
                this.dataForm.updateName = data.bussRtuWarningRole.updateName
                this.dataForm.version = data.bussRtuWarningRole.version
                this.dataForm.gcFlag = data.bussRtuWarningRole.gcFlag
                this.oldvalue = data.bussRtuWarningRole.deptId
                this.dataForm.farmlandInfoIdsname = data.bussRtuWarningRole.relationFarmlandIdsname
                this.yujingyu=data.bussRtuWarningRole.yujingyu
                this.oldvalue = data.bussRtuWarningRole.deptId
                this.strs=JSON.parse(data.bussRtuWarningRole.yjgzJson)
                //this.updatedeptid = data.bussRtuWarningRole.deptId
                this.deptListTreeSetCurrentNode()
              }
            })
          }
        })

      },
      hidep () {
        if(this.dataForm.deptId == ''){
         // this.oldvalue = this.dataForm.deptId
        }else
        if( this.oldvalue != this.dataForm.deptId && this.oldvalue != ''){

          this.$confirm('更换基地将清除田块')
            .then(_ => {
               this.dataForm.relationFarmlandIds = ''
               this.dataForm.farmlandInfoIdsname = ''

              this.oldvalue = this.dataForm.deptId
               this.checki()

          })
          .catch(_ => {
            this.dataForm.deptId  = this.oldvalue
            this.checki()

          });
          }  else if(this.oldvalue == ''){
              this.dataForm.relationFarmlandIds = ''
               this.dataForm.farmlandInfoIdsname = ''
              this.oldvalue = this.dataForm.deptId
               this.checki()

          }
      },
      checki(){
        this.checkedId = this.dataForm.deptId;
        var b = this.$refs.deptListTree.getCheckedNodes(this.checkedId)
        this.$refs.deptListTree.setCheckedNodes([b])
        this.deptListTreeSetCurrentNode();
      },

    // 菜单树设置当前选中节点
      deptListTreeSetCurrentNode () {
        this.$refs.deptListTree.setChecked(this.dataForm.deptId,true,false)
        this.dataForm.deptName = (this.$refs.deptListTree.getCheckedNodes() || [])[0].name
      },
      // 节点修改
      checkChange(data, checked, node){
          if(checked == true){// 选中部门
          //  this.dataForm.farmlandInfoIds = ''

          //     this.dataForm.farmlandInfoIdsname == ''
           //
            this.checkedId = data.id;
            this.$refs.deptListTree.setCheckedNodes([data])
            this.dataForm.deptId = data.id
            this.dataForm.deptName = data.name


          }



      },
      // 菜单树选中
      menuListTreeCurrentChangeHandle (data, node) {



      },
      // // 菜单树设置当前选中节点
      // menuListTreeSetCurrentNode () {

      //   this.$refs.menuListTree.setCurrentKey(this.dataForm.deptId)
      //   this.dataForm.parentName = (this.$refs.menuListTree.getCurrentNode() || {})['name']
      // },
      // // 图标选中
      // iconActiveHandle (iconName) {
      //   this.dataForm.icon = iconName
      // },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid && !this.formLoading) {
            this.formLoading = true
            this.$http({
              url: this.$http.adornUrl(`/buss/bussrtuwarningrole/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'deptId': this.dataForm.deptId,
                'warningLev': this.dataForm.warningLev,
                'name': this.dataForm.name,
                'lowest': this.dataForm.lowest,
                'highest': this.dataForm.highest,
                'standard': this.dataForm.standard,
                'type': this.dataForm.type,
                'startTime': this.dataForm.startTime,
                'endTime': this.dataForm.endTime,
                'relationFarmlandIds': this.dataForm.relationFarmlandIds,
                'createId': this.dataForm.createId,
                'createName': this.dataForm.createName,
                'createTime': this.dataForm.createTime,
                'updateId': this.dataForm.updateId,
                'updateTime': this.dataForm.updateTime,
                'updateName': this.dataForm.updateName,
                'version': this.dataForm.version,
                'gcFlag': this.dataForm.gcFlag,
                'yujingyu':this.yujingyu,
                'yjgzJson':JSON.stringify(this.strs)
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.formLoading = false
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
// 点击输入框选择田块
      changeInput() {
        // this.demoVisible = true
        // if (this.multipleSelection.length == 0) {
        //   this.search()
        // }
        if(this.dataForm.deptId == null||this.dataForm.deptId==''){
           alert('请先选择基地');
           return;
        }
         this.bussfarmlandinfoSelectVisible =true
        this.$nextTick(() => {
          this.$refs.bussfarmlandinfoSelect.init(this.dataForm.relationFarmlandIds,this.dataForm.deptId)
        })
      },
      // 田块选择回调方法
      bussFarmlandInfoSelectChange(ids,names){

          this.dataForm.relationFarmlandIds = ids
          this.dataForm.farmlandInfoIdsname = names
      }

    }
  }
</script>
